import Vue from "vue";
import Vuex from "vuex";
import { setGlobalData, initMicroApp } from "@/initMicroApps";
import { login, getResource, getConfig } from "@/api";
import { encrypt } from "@/utils/crypto";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    appConfig: {
      api:
        process.env.NODE_ENV === "development"
          ? `/api`
          : `${location.origin}/api`,
    },
    loading: false,
    userInfo: {},
    resource: [],
    curApis: [],
    curConfig: {},
  },
  mutations: {
    ["SET_CURCONFIG"](state, data) {
      state.curConfig = data;
    },
    ["SET_CURAPIS"](state, curApis) {
      state.curApis = curApis;
    },
    appConfig(state, data) {
      state.appConfig = data;
    },
    userInfo(state, data) {
      state.userInfo = data;
    },
    resource(state, data) {
      state.resource = data;
    },
    loading(state, data) {
      state.loading = data;
    },
  },
  actions: {
    async userLogin({ commit }, param) {
      localStorage.clear();
      param.password = encrypt(param.password);
      let res = await login(param);
      localStorage.setItem("token", res.token);
      localStorage.setItem("userInfo", JSON.stringify(res));
      commit("userInfo", res);
      setGlobalData({ userInfo: res });
    },
    logOut({ commit }) {
      localStorage.clear();
      commit("userInfo", {});
      commit("resource", []);
    },
    async getResource({ commit }) {
      let resource = await getResource();
      let res = await getConfig("path", "micro_apps");
      let appConfig = {};
      if (res.config) {
        appConfig = res.config.appConfig;
      }
      resource = resource.map((item) => {
        item.meta.activeRule = `#/${item.name}`;

        if (appConfig[item.name]) {
          item.meta = {
            ...item.meta,
            ...appConfig[item.name],
          };
        }

        return {
          ...item,
        };
      });
      initMicroApp(resource);
      commit("resource", resource);
      setGlobalData({ resource, loading: undefined });
    },
  },
  modules: {},
  getters: {
    loading: (state) => state.loading,
    appConfig: (state) => state.appConfig,
    userInfo: (state) => state.userInfo,
    resource: (state) => state.resource,
    curConfig: (state) => state.curConfig,
    curApis: (state) => {
      let obj = {};
      state.curApis.forEach((item) => {
        obj[item.node_name] = item;
      });
      console.log(obj);
      return obj;
    },
  },
});
